Spring Boot多环境单元测试@ActiveProfiles例子

您所在的位置:网站首页 springboot @profile Spring Boot多环境单元测试@ActiveProfiles例子

Spring Boot多环境单元测试@ActiveProfiles例子

#Spring Boot多环境单元测试@ActiveProfiles例子| 来源: 网络整理| 查看: 265

@ActiveProfiles是一个类注解,在Spring单元测试加载ApplicationContext时指定profiles。 @ActiveProfiles有以下参数: profiles: 指定配置文件 resolver: 指定ActiveProfilesResolver,通过代码指定配置文件 value: profiles的别名 inheritProfiles: 配置文件是否继承父类,默认为true

@ActiveProfiles 在单元测试中使用的例子:

@ExtendWith(SpringExtension.class) @ActiveProfiles("prod") @ContextConfiguration public class ActiveProfileTest { ------ }

如果想通过@ActiveProfiles指定多个配置文件,把单元测试和对应环境的配置分开然后组合起来,可以指定一个数组:

@ExtendWith(SpringExtension.class) @ActiveProfiles({ "prod", "junit" }) @ContextConfiguration public class ActiveProfileTest { ------ } 在spring boot中使用单元测试

我们使用@ActiveProfiles 和 @SpringBootTest。@SpringBootTest是一个类注解,在springboot应用中用来创建一个测试类:

ActiveProfileTest.java

package com.concretepage; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.test.context.ActiveProfiles; import com.concretepage.services.Animal; @ActiveProfiles({ "prod", "lion" }) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class ActiveProfileTest { @Autowired private Animal animal; @Autowired private TestRestTemplate restTemplate; @Test public void serviceTest() { String message = animal.getMessage(); assertTrue("Hello Lion!".equals(message)); } @Test public void webAppTest() { String url = "http://localhost:8585/spring-boot-prod/"; String body = this.restTemplate.getForObject(url, String.class); assertTrue("Hello Lion!".equals(body)); } }


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3